<?php namespace App\Http\Controllers\admin\uc;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Users;
use App\Models\Technologies;
use Illuminate\Http\Request;
use Input;
use App\Models\UserProfile;
use App\Models\Cellphone;
use App\Models\Email;
use App\Models\Area;
use DB;
use App\Models\AssociationBase;
use App\Models\DevicetechProviderBase;
use App\Models\EnterpriceEnergysaverBase;
use App\Models\EnterpricePowerusersBase;
use App\Models\GovernmentBase;
use App\Models\ThirdpartyBase;
use Validator;
use App\Models\Techs;
use App\Models\Domains;
use App\Models\SaverDomain;
use App\Models\SaverTech;
use App\Models\EnterpriceEnergysaverIndustry;
use App\Models\ThirdpartyIndustry;
use App\Models\DevicetechProviderIndustry;
use App\Models\ThirdpartyProfessionalList;
use App\Models\ThirdpartyDevice;
use App\Models\ThirdpartyHistoryProject;
use App\Models\Projects;
use App\Models\Devices;
use Redirect;
use Session;






class UserController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */


 
	public function index()
	{  
		if(Session::has('admin')){
		   return view("admin.uc.index")->withIsUserlist(true);
     }else{
      return Redirect::to('admin/dologin');
     }
	}

  public function audit()
  {
    $validate_state = Input::get("validate_state");
    $uid = Input::get("uid");
    $model = Users::where("id", $uid);
    if($model->count()){
      $model->update(["validate_state" => $validate_state]);
      return $this->json([]);
    }
  }

	public function userMessage()
	{
		$uid = Input::get("uid");
		$role_id = Users::where("id", $uid)->pluck("role_id");
		$province = Area::where("parent_id", 1)->get()->toArray();
		$domains = Domains::where("parent_id", 0)->get()->toArray();
		$techs = Techs::all()->toArray();

        switch ($role_id) {
          case env("SAVER"):
            $ind_model = EnterpriceEnergysaverIndustry::with(["saverTech", "saverTech.techs", "saverDomain", "saverDomain.domain", "saverDomain.domain.parent"])->where('uid', $uid);
            break;
          case env("THIRD"):
            $ind_model = ThirdpartyIndustry::where('uid', $uid);
            break;
          case env("DEVICE_TECH"):
            $ind_model = DevicetechProviderIndustry::where('uid', $uid);
            break;
          default:
            break;
        }

        if(isset($ind_model)){
          $ind_data = $ind_model->first();
        }else{
          $ind_data = [];
        }
        // dd($ind_data);
		return view("admin.uc.message", ["province" => $province, "role_id" => $role_id, "domains" => $domains, "techs" => $techs, "ind_data" => $ind_data])->withIsUserlist(true);
	}



	public function getUserList()
	{
		$current = Input::get("current");
		$rowCount = Input::get("rowCount");
		$sort = Input::get("sort")["id"];
		$sort = $sort ? $sort : "desc";
		$keywords = trim(Input::get('searchPhrase'));
		$model = DB::table("users as u")->leftJoin("user_profile as uf", "u.id", "=", "uf.uid")->leftJoin("cellphone as ce", "u.id", "=", "ce.uid")->leftJoin("email as em", "u.id", "=", "em.uid")->select("u.id as u_id", "u.role_id", "u.validate_state", "u.state", "uf.nickname", "uf.contact_way", "ce.cell_phone", "em.email")->where("u.role_id", "!=", env("DEVELOPMENT"));

		if($keywords){
			$model = $model->where(function($query) use ($keywords){
				$query->orWhere("uf.nickname", "like", "%".$keywords."%")->orWhere("ce.cell_phone", "like", "%".$keywords."%")->orWhere("em.email", "like", "%".$keywords."%");
			});
			$count = $model->count();
			$user = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get();


		}else{
			$count = $model->count();
			$user = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get();
		}

		return array(
			"current" => $current,
			"rowCount" => $rowCount,
			"rows" => $user,
			"total" => $count
		);

	}


  	public function getUserProfile()
  	{
  	    $uid = Input::get("uid");
  	    $model = Users::with(["profile"])->where("id", $uid);
  	    if($model->count())
  	    {
  	    	$data = $model->get()[0]->toArray();
  	    	return $this->json(["data" => $data]);
  	    }
  	}

  	public function updateProfile()
  	{
  		$uid = Input::get("uid");
  		$user = Users::where("id", $uid);
  		if($user->count())
  		{
  			$userData = Input::only("state", "freeze_duration", "freeze_time");
  			$user->update($userData);
  			$profile = UserProfile::where("uid", $uid);
  			$profileData = Input::only("nickname", "contact_way", "email", "address", "province", "city", "area", "sex");
  			$profile->update($profileData);
  			return $this->json([]);
  		}
  	}



  	public function getUserGroup()
  	{
  		$uid = Input::get("uid");
  		$role_id = Users::where("id", $uid)->pluck("role_id");
  		switch ($role_id) {
  			case env("ENERGY"):
  				$data = EnterpricePowerusersBase::where("uid", $uid)->first();
  			break;
  			case env("SAVER"):
  				$data = EnterpriceEnergysaverBase::where("uid", $uid)->first();
  			break;
  			case env("DEVICE_TECH"):
  				$data = DevicetechProviderBase::where("uid", $uid)->first();
  			break;
  			case env("THIRD"):
  				$data = ThirdpartyBase::where("uid", $uid)->first();
  			break;
  			case env("ASSOCIATION"):
  				$data = AssociationBase::where("uid", $uid)->first();
  			break;
  			case env("GOVERNMENT"):
  				$data = GovernmentBase::where("uid", $uid)->first();
  			break;
  			default:
  				$data = [];
  			break;
  		}

  		if($data){
  			return $this->json(["data" => $data]);
  		}
  	}


  	public function updateGroup()
  	{
  		$uid = Input::get('uid');
  		$rule =[];
  		$msg = [];
  		$validator = Validator::make(Input::all(), $rule, $msg);
  		if($validator->passes()){

  			$role_id = Users::where("id", $uid)->pluck("role_id");
  			switch ($role_id) {
  				case env("ENERGY"):
  					$model = EnterpricePowerusersBase::where("uid", $uid);
  				break;
  				case env("SAVER"):
  					$model = EnterpriceEnergysaverBase::where("uid", $uid);
  				break;
  				case env("DEVICE_TECH"):
  					$model = DevicetechProviderBase::where("uid", $uid);
  				break;
  				case env("THIRD"):
  					$model = ThirdpartyBase::where("uid", $uid);
  				break;
  				case env("ASSOCIATION"):
  					$model = AssociationBase::where("uid", $uid);
  				break;
  				case env("GOVERNMENT"):
  					$model = GovernmentBase::where("uid", $uid);
  				break;
  				default:
  					return;
  				break;
  			}

  			if($model->count()){
  				switch ($role_id) {
  					case ($role_id == env("ASSOCIATION") || $role_id == env("GOVERNMENT")):
  						$data = Input::only('company_name', 'group_code','contact_person','contact_number','province','city','area','address','zcode','fax','email','induction','regist_copy', 'logo','description');
	  					$imgArr = Input::only("regist_copy", "logo");
  						break;
  					default:
	  					$data = Input::only('company_name', 'contact_number','contact_person','email','enterprice_char','enterprice_pic','fax','group_code','group_code_img','induction','legal_person','regist_address','regist_area','regist_capital', 'regist_city','regist_code','regist_copy','logo','regist_province','regist_time','zcode', 'description');
	  					$imgArr = Input::only("group_code_img", "regist_copy", "enterprice_pic", "logo");
  						break;
  				}
  				$this->moveImages($imgArr, env("OTHERS_DIR"), $uid);
  				$model->update($data);
  				return $this->json([]);
  			}

  		}else{
  			// return self::error(self::DATA_IS_WRONG);
  		}
  	}


  	public function getUserIndustry()
  	{
  		$uid = Input::get("uid");
  		$role_id = Users::where("id", $uid)->pluck("role_id");

  		switch ($role_id) {
  			case env("SAVER"):
  				$model = EnterpriceEnergysaverIndustry::with(["saverTech", "saverDomain", "saverDomain.domain"])->where('uid', $uid);
  				break;
        case env("THIRD"):
          $model = ThirdpartyIndustry::where('uid', $uid);
          break;
        case env("DEVICE_TECH"):
          $model = DevicetechProviderIndustry::where('uid', $uid);
          break;
  			default:
          return;
  				break;
  		}

  		if($model->count()){
  			$data = $model->get()[0]->toArray();
  			return $this->json(["data" => $data]);
  		}
  	}


    public function updateIndustry()
    {
      $rule = array();
      $msg = array();
      $validator = Validator::make(Input::all(), $rule, $msg);
      if($validator->passes()){
        $uid = Input::get("uid");
        $model = EnterpriceEnergysaverIndustry::where('uid', $uid);
        if($model->count()){
          $data = Input::except('domains', 'techs', "uid");
          $imgArr = Input::only("bank_credit_copy");
          $this->moveImages($imgArr, env("OTHERS_DIR"), $uid);
          $saver_id = $model->get()[0]->id;
          $model->update($data);
          $domain_model = SaverDomain::where("saver_id", $saver_id);
          $domain_model->delete();
          $tech_model = SaverTech::where("saver_id", $saver_id);
          $tech_model->delete();

          $techs = Input::get("techs");
          $domains = Input::get("domains");
          foreach ($techs as $tech)
          {
            SaverTech::create(["cate_id" => $tech, "saver_id" => $saver_id]);
          }
          foreach ($domains as $domain)
          {
            SaverDomain::create(["cate_id" => $domain, "saver_id" => $saver_id]);
          }
          return $this->json([]);
        }
      }else{
        $errors = $validator->messages();
        return self::error($error->first());
      }
    }


    public function updateIndustryDevice()
    {
      $rule = array();
      $msg = array();
      $validator = Validator::make(Input::all(), $rule, $msg);
      if($validator->passes()){
        $uid = Input::get("uid");
        $model = DevicetechProviderIndustry::where('uid', $uid);
        if($model->count()){
          $data = Input::except('imgFile', "uid");

          $imgArr = Input::only("bank_credit_copy");
          $this->moveImages($imgArr, env("OTHERS_DIR"), $uid);

          $model->update($data);
          return $this->json([]);
        }
      }else{
        return self::error(self::DATA_IS_WRONG);
      }
    }


    public function thirdPersonList()
    {
      $uid = Input::get("uid");
      $current = Input::get("current");
      $rowCount = Input::get("rowCount");
      $sort = Input::get("sort")["id"];
      $sort = $sort ? $sort : "desc";

      $ind_id = ThirdpartyIndustry::where("uid", $uid)->pluck("id");

      $model = ThirdpartyProfessionalList::where("industry_id", $ind_id);
      $count = $model->count();
      $data = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
      return array(
        "current" => $current,
        "rowCount" => $rowCount,
        "rows" => $data,
        "total" => $count
      );
    }

    public function thirdDeviceList()
    {
      $uid = Input::get("uid");
      $current = Input::get("current");
      $rowCount = Input::get("rowCount");
      $sort = Input::get("sort")["id"];
      $sort = $sort ? $sort : "desc";

      $ind_id = ThirdpartyIndustry::where("uid", $uid)->pluck("id");

      $model = ThirdpartyDevice::where("industry_id", $ind_id);
      $count = $model->count();
      $data = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
      return array(
        "current" => $current,
        "rowCount" => $rowCount,
        "rows" => $data,
        "total" => $count
      );
    }

    public function thirdProjectList()
    {
      $uid = Input::get("uid");
      $current = Input::get("current");
      $rowCount = Input::get("rowCount");
      $sort = Input::get("sort")["id"];
      $sort = $sort ? $sort : "desc";

      $ind_id = ThirdpartyIndustry::where("uid", $uid)->pluck("id");

      $model = ThirdpartyHistoryProject::where("industry_id", $ind_id);
      $count = $model->count();
      $data = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
      return array(
        "current" => $current,
        "rowCount" => $rowCount,
        "rows" => $data,
        "total" => $count
      );
    }

    public function getUserProject()
    {
      $uid = Input::get("uid");
      $current = Input::get("current");
      $rowCount = Input::get("rowCount");
      $sort = Input::get("sort")["id"];
      $sort = $sort ? $sort : "desc";


      $model = Projects::where("uid", $uid);
      $count = $model->count();
      $data = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
      return array(
        "current" => $current,
        "rowCount" => $rowCount,
        "rows" => $data,
        "total" => $count
      );
    }

    public function getUserDevice()
    {
      $uid = Input::get("uid");
      $current = Input::get("current");
      $rowCount = Input::get("rowCount");
      $sort = Input::get("sort")["id"];
      $sort = $sort ? $sort : "desc";


      $model = Devices::where("uid", $uid);
      $count = $model->count();
      $data = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
      return array(
        "current" => $current,
        "rowCount" => $rowCount,
        "rows" => $data,
        "total" => $count
      );
    }

    public function getUserTech()
    {
      $uid = Input::get("uid");
      $current = Input::get("current");
      $rowCount = Input::get("rowCount");
      $sort = Input::get("sort")["id"];
      $sort = $sort ? $sort : "desc";


      $model = Technologies::where("uid", $uid);
      $count = $model->count();
      $data = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
      return array(
        "current" => $current,
        "rowCount" => $rowCount,
        "rows" => $data,
        "total" => $count
      );
    }

    public function getProjectFinance()
    {
      $uid = Input::get("uid");
      $current = Input::get("current");
      $rowCount = Input::get("rowCount");
      $sort = Input::get("sort")["id"];
      $sort = $sort ? $sort : "desc";


      $model = Projects::with(["financing"])->where("uid", $uid)->where("is_financing", 1);
      $count = $model->count();
      $data = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get();


      foreach ($data as $key => $value) {
        $value["fin_id"] = $value["financing"]["id"];
      }
      return array(
        "current" => $current,
        "rowCount" => $rowCount,
        "rows" => $data,
        "total" => $count
      );
    }



    public function editArtisan()
    {
      return view('admin.uc.edit_artisan')->withIsUserlist(true);
    }

    public function editInstrument()
    {
      return view('admin.uc.edit_instrument')->withIsUserlist(true);
    }

    public function editProjects()
    {
      return view('admin.uc.edit_projects')->withIsUserlist(true);
    }


    public function saveArtisan()
    {
      $uid = Input::get("uid");
      $indid = ThirdpartyIndustry::where("uid", $uid)->pluck("id");
      $data = Input::all();
      $data['industry_id'] = $indid;
      if(ThirdpartyProfessionalList::create($data)){
        return $this->json([]);
      }

    }

    public function getArtisan()
    {
      $pid = Input::get("pid");
      $model = ThirdpartyProfessionalList::where("id", $pid);
      if($model->count())
      {
        $data = $model->first()->toArray();
        return $this->json($data);
      }
      else
      {
        return;
      }
    }

    public function updateArtisan()
    {
      $data = Input::except("pid", "uid");
      $pid = Input::get("pid");
      $model = ThirdpartyProfessionalList::where("id", $pid);
      if($model->count()){
        $model->update($data);
        return $this->json([]);
      }else{
        return;
      }
    }

    public function deleteArtisan()
    {
      $pid = Input::get("pid");
      $model = ThirdpartyProfessionalList::where("id", $pid);
      if($model->count())
      {
        $model->delete();
        return $this->json([]);
      }
      else
      {
        return;
      }
    }


    public function addInstrument()
    {
      $uid = Input::get("uid");
      $industry = ThirdpartyIndustry::where("uid", $uid);
      if($industry->count())
      {
        $indid = $industry->pluck("id");
        $data = Input::all();
        $data['industry_id'] = $indid;
        ThirdpartyDevice::create($data);
        return $this->json([]);
      }
      else
      {
        return;
      }
    }


    public function getInstrument()
    {
      $tid = Input::get("tid");
      $model = ThirdpartyDevice::where("id", $tid);
      if($model->count())
      {
        $data = $model->first()->toArray();
        return $this->json($data);
      }
      else
      {
        return;
      }
    }

    public function updateInstrument()
    {
      $data = Input::except("tid", "uid");
      $tid = Input::get("tid");
      $model = ThirdpartyDevice::where("id", $tid);
      if($model->count())
      {
        $model->update($data);
        return $this->json([]);
      }
      else
      {
        return;
      }
    }

    public function deleteInstrument()
    {
      $tid = Input::get("tid");
      $model = ThirdpartyDevice::where("id", $tid);
      if($model->count())
      {
        $model->delete();
        return $this->json([]);
      }
      else
      {
        return;
      }
    }


    public function addProjects()
    {
      $uid = Input::get("uid");
      $industry = ThirdpartyIndustry::where("uid", $uid);
      if($industry->count())
      {
        $indid = $industry->pluck("id");
        $data = Input::all();
        $data['industry_id'] = $indid;
        ThirdpartyHistoryProject::create($data);
        return $this->json([]);
      }
      else
      {
        return;
      }
    }


    public function getProjects()
    {
      $hid = Input::get("hid");
        $model = ThirdpartyHistoryProject::where("id", $hid);
        if($model->count())
        {
          $data = $model->get()[0]->toArray();
          return $this->json($data);
        }
        else
        {
          return;
        }
    }


    public function updateProjects()
    {
      $hid = Input::get("hid");
      $data = Input::except("hid", "uid");
      $model = ThirdpartyHistoryProject::where("id", $hid);
      if($model->count())
      {
        $model->update($data);
        return $this->json([]);
      }
      else
      {
        return;
      }
    }

    public function deleteProjects()
    {
      $hid = Input::get("hid");
      $model = ThirdpartyHistoryProject::where("id", $hid);
      if($model->count())
      {
        $model->delete();
        return $this->json([]);
      }
      else
      {
        return;
      }
    }





	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

}
